import { _path, existplayer } from '../../mode/allapi'
import { AMessage, obtainingImages, plugin ,RedisA} from '../../api/api'
import { delplayer, setplayer, setredis } from './player.js'
const reStart = {}

export class user extends plugin {
  constructor() {
    super({
      dsc: '起兵',
      rule: [
        {
          reg: /^(#|\/)?开启征途*$/,
          fnc: 'start'
        },
        {
          reg: /^(#|\/)?再起征途*$/,
          fnc: 'agestart'
        }
      ]
    })
  }
  async start(e: AMessage) {
    const id = e.user_id
    if (!(await existplayer(id))) {
      await setplayer(id)
      e.reply('恭喜主公起兵成功')
    }
    const data = {
      HData: (await _path(id)).player
    }
    const img = await obtainingImages(
      '/resources/html/player/player.html',
      data
    ).catch(err => {
      console.log(err)
      return '未知错误'
    })
    if (img) e.reply(img).catch(err => console.log(err))
    return true
  }
  async agestart(e: AMessage) {
    const id = e.user_id
    if (!(await existplayer(id))) return false
    const redistime = await RedisA.ttl(`age:time${id}:@1.2`)
    if (redistime != -2 && redistime != -1) {
      const hoursRemaining = Math.floor(redistime / 60) 
      return e.reply(`主公: 请勿频繁，还有${hoursRemaining}分钟后可再次尝试`)
    }
    if (!reStart[id] || reStart[id] + 60000 < new Date().getTime()) {
      reStart[id] = new Date().getTime()
      e.reply([
        e.segment.at(e.user_id),
        '\n主公:请60秒内发送[(#|/)再起征途]',
        '\n以确认再起~'
      ]).catch((err: any) => {
        console.error(err)
        return
      })
      return true
    }
    await delplayer(id)
    await setplayer(id)
    await setredis(id)
    const data = {
      HData: (await _path(id)).player
    }
    const img = await obtainingImages(
      '/resources/html/player/player.html',
      data
    ).catch(err => {
      console.log(err)
      return '未知错误'
    })
    if (img) e.reply(img)
  }
}
